<template>
  <el-dialog
    top="10vh"
    width="500px"
    title="添加/编辑"
    :visible.sync="dialogValue"
    :close-on-click-modal="false"
    append-to-body
  >
    <SubmitForm
      :rule-form="ruleForm"
      :rules="rules"
      :form-list="formList"
      @change="handleFormChange"
      @save="onSave"
      @close="dialogValue = false"
    />

  </el-dialog>
</template>

<script>
import { http } from '@/api'
export default {
  name: 'FormAdd',
  data() {
    return {
      apiKey: 'member',
      dialogValue: false,
      ruleForm: {
      },
      defaultForm: {
        company_id: '',
        nickname: '',
        avatar_url: '',
        username: '',
        password: '',
        status: 1
      },
      rules: {
        company_id: [
          { required: true, message: '请选择企业', trigger: 'blur' }
        ],
        nickname: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ],
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
      },
      formList: [
        {
          key: 'company_id',
          name: 'select',
          label: '所属企业',
          options: [],
          colSpan: 24
        },
        {
          key: 'nickname',
          name: 'input',
          label: '姓名',
          colSpan: 24
        },
        {
          key: 'username',
          name: 'input',
          label: '账号',
          colSpan: 12
        },
        {
          key: 'password',
          name: 'input',
          label: '密码',
          type: 'password',
          colSpan: 12
        },
        {
          key: 'avatar_url',
          name: 'file',
          multiple: false,
          defaultValue: '',
          label: '头像',
          colSpan: 12
        },
        {
          key: 'status',
          name: 'switch',
          label: '是否启用',
          activeValue: 1,
          inactiveValue: 0,
          colSpan: 24
        }
      ]
    }
  },
  created() {
    http.company.list().then(res => {
      this.formList[0].options = res.data.map(item => {
        return {
          value: item.id,
          name: item.name
        }
      })
    })
  },
  methods: {
    handleFormChange({ key, val }) {

    },
    open(row) {
      this.dialogValue = true
      if (row) {
        http[this.apiKey].read(row.id).then(res => {
          this.ruleForm = {
            ...res.data
          }
        })
      } else {
        this.ruleForm = {
          ...this.defaultForm
        }
      }
    },
    onSave() {
      http[this.apiKey][this.ruleForm.id ? 'update' : 'create'](this.ruleForm.id, { ...this.ruleForm, role: 'company' }).then(res => {
        this.$message.success('操作成功')
        this.dialogValue = false
        this.$emit('get-page')
      })
    }
  }
}
</script>

<style scoped lang="scss">
</style>
